package com.aicheyoudao;

import java.util.ArrayList;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.CheckBox;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.aicheyoudao.MyApplication.locationFinishListener;
import com.aicheyoudao.MyAsyncTask.onloadlistener;
import com.aicheyoudao.utils.NavigationUtil;
import com.aicheyoudao.utils.SearchUtils;
import com.aicheyoudao.utils.SearchUtils.searchResListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.PoiOverlay;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.navisdk.BNaviPoint;

public class MainMap extends Activity implements searchResListener,
		OnClickListener, onloadlistener, OnCheckedChangeListener {

	private MapView mMapView;
	private BaiduMap mBaiduMap;
	// 定位相关
	// private LocationMode mCurrentMode;
	// private BitmapDescriptor mCurrentMarker;
	boolean isFirstLoc = true;// 是否首次定位
	private String searchKey;
	private SDKReceiver mReceiver;
	private BDLocation mlocation;

	// private int type = 0;
	// public final static int TYPE_SHOW_SEARCH = 1;
	// public final static int TYPE_SHOW_SINGLE = 2;
	// public final static String KEY_TYPE = "type";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.map);
		// type = getIntent().getIntExtra(KEY_TYPE, 0);
		searchKey = getIntent().getStringExtra("searchKey");
		Log.i("info", "searchkey=" + searchKey);
		if (!MyApplication.getInstance().getmLocClient().isStarted()) {
			MyApplication.getInstance().getmLocClient().start();
		}
		initView();
		initSdk();
		// if (TYPE_SHOW_SEARCH == type) {
		initLocation();
		// }
		if (!MyApplication.getInstance().ismIsEngineInitSuccess()) {
			MyApplication.getInstance().initNavigation(this);
		}
	}

	private void initView() {
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();
		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);

		TextView search = (TextView) findViewById(R.id.map_search);
		TextView near = (TextView) findViewById(R.id.map_near);
		CheckBox traffic = (CheckBox) findViewById(R.id.map_traffic);
		TextView mylocation = (TextView) findViewById(R.id.map_mylocation);
		mylocation.setOnClickListener(this);
		search.setOnClickListener(this);
		near.setOnClickListener(this);
		traffic.setOnCheckedChangeListener(this);
	}

	private void initSdk() {
		IntentFilter iFilter = new IntentFilter();
		iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
		iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
		mReceiver = new SDKReceiver();
		registerReceiver(mReceiver, iFilter);

	}

	/**
	 * 初始化定位的相关设置
	 */
	private void initLocation() {
		MyApplication.getInstance().setonlocationFinishListener(
				new locationFinishListener() {

					@Override
					public void ReceiveLocation(BDLocation location) {

						// map view 销毁后不在处理新接收的位置
						if (location == null || mMapView == null
								|| mBaiduMap == null)
							return;
						MyLocationData locData = new MyLocationData.Builder()
								.accuracy(location.getRadius())
								// 此处设置开发者获取到的方向信息，顺时针0-360
								.direction(100)
								.latitude(location.getLatitude())
								.longitude(location.getLongitude()).build();
						mBaiduMap.setMyLocationData(locData);
						LatLng latLng = new LatLng(location.getLatitude(),
								location.getLongitude());
						mlocation = location;
						if (isFirstLoc) {
							isFirstLoc = false;
							// String city = location.getCity();
							// Log.i("info", city);
							MapStatusUpdate u = MapStatusUpdateFactory
									.newLatLng(latLng);
							mBaiduMap.animateMapStatus(u);
							SearchUtils.getSearchUtils().setsearchResListener(
									MainMap.this);
							SearchUtils.getSearchUtils().PoiNearSearch(latLng,
									searchKey);
							MyLoadingDialog
									.StartShowProgressDialog(MainMap.this);
						} else {
							// mLocClient.stop();

						}

					}
				});

	}

	/**
	 * 构造广播监听类，监听 SDK key 验证以及网络异常广播
	 */
	public class SDKReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			String s = intent.getAction();
			if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
				Toast.makeText(MainMap.this,
						"key 验证出错! 请在 AndroidManifest.xml 文件中检查 key 设置",
						Toast.LENGTH_SHORT).show();
			} else if (s
					.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
				Toast.makeText(MainMap.this, "网络出错", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	protected void onDestroy() {

		unregisterReceiver(mReceiver);
		// 退出时销毁定位
		MyApplication.getInstance().getmLocClient().stop();
		mBaiduMap.setMyLocationEnabled(false);
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		mMapView.onDestroy();
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
		mMapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
		mMapView.onPause();
	}

	private PoiInfo clickPoi;

	private class MyPoiOverlay extends PoiOverlay {

		public MyPoiOverlay(BaiduMap baiduMap) {
			super(baiduMap);
		}

		@Override
		public boolean onPoiClick(int index) {
			super.onPoiClick(index);
			PoiInfo poi = getPoiResult().getAllPoi().get(index);
			clickPoi = poi;
			MyAsyncTask task = new MyAsyncTask(MainMap.this);
			task.setOnloadlistener(MainMap.this);
			task.execute(poi.name);
			return true;
		}
	}

	private TextView navigate;
	private TextView goDetail;
	private PopupWindow popu;

	@SuppressLint("InflateParams")
	public void showPoiInfoDialog(shopBean shopinfo) {
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.shop_info_dialog, null);
		TextView shopName = (TextView) view.findViewById(R.id.info_name);
		shopName.setText(shopinfo.getShopName());
		TextView phone = (TextView) view.findViewById(R.id.info_phoneNum);
		phone.setText(shopinfo.getPhoneNum());
		TextView address = (TextView) view.findViewById(R.id.info_address);
		address.setText(shopinfo.getAddress());
		RatingBar leavl = (RatingBar) view.findViewById(R.id.info_level);
		goDetail = (TextView) view.findViewById(R.id.info_showDetails);
		goDetail.setTag(shopinfo);
		goDetail.setOnClickListener(this);
		navigate = (TextView) view.findViewById(R.id.ifno_goNavigate);
		navigate.setTag(shopinfo);
		navigate.setOnClickListener(this);
		popu = new PopupWindow(view, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT, true);
		popu.setBackgroundDrawable(new PaintDrawable());
		popu.setOutsideTouchable(true);
		popu.showAtLocation(mMapView, Gravity.BOTTOM, 0, 0);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.map_search:
			Intent search = new Intent(MainMap.this, SearchMainActivity.class);
			this.startActivity(search);
			break;

		case R.id.map_near:
			Intent near = new Intent(MainMap.this, NearActivity.class);
			this.startActivity(near);
			break;

		case R.id.info_showDetails:
			break;

		case R.id.ifno_goNavigate:
			Log.i("info", "开始导航");
			// 导航初始化成功
			popu.dismiss();
			shopBean Navi = (shopBean) navigate.getTag();
			BNaviPoint start = new BNaviPoint(mlocation.getLongitude(),
					mlocation.getLatitude(), mlocation.getAddrStr(),
					BNaviPoint.CoordinateType.BD09_MC);
			BNaviPoint end = new BNaviPoint(Navi.getLocation().longitude,
					Navi.getLocation().latitude, Navi.getAddress(),
					BNaviPoint.CoordinateType.BD09_MC);
			NavigationUtil.start(MainMap.this, start, end);
			break;
		case R.id.map_mylocation:
			setMylocationToMiddle();
			break;
		}
	}

	@Override
	public void loadFinish(String res) {
		shopBean shop;
		try {
			ArrayList<shopBean> shops = Parser.parseSerPoi(res);
			if (shops.size() > 0) {
				shop = shops.get(0);
				shop.setLocation(clickPoi.location);
			} else {
				shop = new shopBean();
				shop.setShopName(clickPoi.name);
				shop.setPhoneNum(clickPoi.phoneNum);
				shop.setAddress(clickPoi.address);
				shop.setLocation(clickPoi.location);
			}
			showPoiInfoDialog(shop);

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void searchSucess(PoiResult result) {
		MyLoadingDialog.stopDialog();
		if (result == null
				|| result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
			return;
		}
		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			mBaiduMap.clear();
			PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
			mBaiduMap.setOnMarkerClickListener(overlay);
			overlay.setData(result);
			overlay.addToMap();
			// 缩放地图，使所有Overlay都在合适的视野内
			overlay.zoomToSpan();
			return;
		}
		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

			// 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
			String strInfo = "在";
			for (CityInfo cityInfo : result.getSuggestCityList()) {
				strInfo += cityInfo.city;
				strInfo += ",";
			}
			strInfo += "找到结果";
			Toast.makeText(MainMap.this, strInfo, Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton checkbox, boolean isChecked) {
		if (isChecked) {
			// 开启路况
			mBaiduMap.setTrafficEnabled(true);
			checkbox.setText("路况开");

		} else {
			// 关闭路况
			mBaiduMap.setTrafficEnabled(false);
			checkbox.setText("路况关");
		}
	}

	// private void addMark() {
	// // 定义Maker坐标点
	// LatLng point = new LatLng(39.963175, 116.400244);
	// // 构建Marker图标
	// BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource();
	// // 构建MarkerOption，用于在地图上添加Marker
	// OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
	// // 在地图上添加Marker，并显示
	// mBaiduMap.addOverlay(option);
	// }

	public void setMylocationToMiddle() {
		BDLocation location = MyApplication.getInstance().getMlocation();
		if (location == null || mMapView == null || mBaiduMap == null)
			return;
		MyLocationData locData = new MyLocationData.Builder()
				.accuracy(location.getRadius()).direction(100)
				.latitude(location.getLatitude())
				.longitude(location.getLongitude()).build();
		mBaiduMap.setMyLocationData(locData);
		LatLng latLng = new LatLng(location.getLatitude(),
				location.getLongitude());
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(latLng);
		mBaiduMap.animateMapStatus(u);
		SearchUtils.getSearchUtils().setsearchResListener(MainMap.this);
		SearchUtils.getSearchUtils().PoiNearSearch(latLng, searchKey);
		MyLoadingDialog.StartShowProgressDialog(MainMap.this);
	}

}
